package app.lockenabler;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.Vibrator;
import android.provider.Settings.SettingNotFoundException;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;

public class LockEnabler extends Activity {
	
	private Timer timer;
	private int count;
	private Vibrator vibrator;
	static int defaultimeout;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if (Options.getDevice().equalsIgnoreCase("HTC Desire")){
        	Options.setSettingsInt("Lock_Screen_Time_Out", 5, LockEnabler.this);
        }
        
        count = Options.getSettingsInt("Lock_Screen_Time_Out", 2, LockEnabler.this)+1;
           	
        RelativeLayout RST = (RelativeLayout)findViewById(R.id.layout);
        RST.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
            reset();
            }
         });        

        Button STGS = (Button) findViewById(R.id.settings);
        
        if (Options.getSettingsBoolean("Exit_On_Touch", false, LockEnabler.this)){
        	STGS.setText(getString(R.string.touch_settings));
        }
        
        STGS.setOnLongClickListener(new View.OnLongClickListener(){
			public boolean onLongClick(View v) {
				Intent i = new Intent(LockEnabler.this, Settings.class);
		        startActivity(i);
				return false;
			}
        });
        STGS.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   Options.mess(getString(R.string.long_mess), LockEnabler.this);
        	   reset();
           }
        });
        STGS.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				reset();
				return false;
			}
         });
        
        ImageButton DNT = (ImageButton) findViewById(R.id.donate_button);
       		
        DNT.setOnLongClickListener(new View.OnLongClickListener(){
			public boolean onLongClick(View v) {
				Intent i = new Intent(LockEnabler.this, Donate.class);
		        startActivity(i);
				return false;
			}
        });
        DNT.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   Options.mess(getString(R.string.long_mess), LockEnabler.this);
        	   reset();
           }
        });
        DNT.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				reset();
				return false;
			}
         });
        
        try {
    		defaultimeout=android.provider.Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT);
    	} catch (SettingNotFoundException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    	android.provider.Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0);
        
    	timer = new Timer();
    	timer.scheduleAtFixedRate(new TimerUpdate(), 0, 1000);
    }
    
    @Override
    protected void onStop() {
 	   super.onStop();
 	   restore();
    }
    
    @Override
    protected void onPause() {
 	   super.onPause();
 	   finish();
    }
    
    @Override
    public boolean onKeyDown(int key, KeyEvent kc){
    	if (Options.getSettingsBoolean("Exit_On_Touch", false, LockEnabler.this)){
    		switch (key){
        	case KeyEvent.KEYCODE_HOME:
 			   restore();
 			   finish();
            break;
        	case KeyEvent.KEYCODE_BACK:
  			   restore();
  			   finish();
            break;
        	case KeyEvent.KEYCODE_DPAD_CENTER:
        		Intent i = new Intent(LockEnabler.this, Settings.class);
		        startActivity(i);
             break;
        	default:
        		reset();
        	}
        }
    	else{
        	switch (key){
        	case KeyEvent.KEYCODE_HOME:
 			   restore();
 			   finish();
            break;
        	case KeyEvent.KEYCODE_BACK:
        		Options.mess(getString(R.string.exit_mess), LockEnabler.this);
        		reset();
            break;
        	default:
        		reset();
        	}
 	   }
 	   return true;
 	}

    final class TimerUpdate extends TimerTask {
        public void run() {
            Timer.sendMessage(Message.obtain(Timer));
        }
    }
    
    private Handler Timer = new Handler() {
        public void handleMessage(Message msg) {
            if (count >= 1) {
            	TextView CNTR = (TextView)findViewById(R.id.counter);
            	CNTR.setText(""+count);
            	if (count == 1){
                	screenOff();
                }
                count--;
            }
            else {
                if (timer != null) {
                    timer.cancel();
                    timer.purge();
                    finish();
                }
            }
        }
   };
   
   private void screenOff(){
	   WindowManager.LayoutParams sleep = getWindow().getAttributes();
	   sleep.screenBrightness = 0 / 100.0f;
	   getWindow().setAttributes(sleep);
   }
   
   private void restore(){
	   android.provider.Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, defaultimeout);
   }

   private void reset(){
	   if (Options.getSettingsBoolean("Vibration_Notification", true, LockEnabler.this)){
		   vibra(50);
	   }
	   if (Options.getSettingsBoolean("Exit_On_Touch", false, LockEnabler.this)){
		   finish();
	   }
	   else{
		   count = Options.getSettingsInt("Lock_Screen_Time_Out", 2, LockEnabler.this)+1;
	   }
   }
   
   private void vibra(long i){
	   vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	   vibrator.vibrate(i);
   }
}
